<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-17 18:02:29
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-17 21:15:50
 * @FilePath: /free-learning-front/src/views/AccountSettingView.vue
 * @Description: 账号设置页面
-->
<template>
  <div class="account-settings-container">
    <!-- 修改密码 -->
    <div class="settings-section">
      <h3>
        <el-icon><Lock /></el-icon> 修改密码
      </h3>
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        class="settings-form"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><EditPen /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Check /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleChangePassword"
            :loading="passwordLoading"
          >
            <el-icon><RefreshRight /></el-icon> 修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 邮箱绑定 -->
    <div class="settings-section">
      <h3>
        <el-icon><Message /></el-icon> 邮箱绑定
      </h3>
      <el-form
        ref="emailFormRef"
        :model="emailForm"
        :rules="emailRules"
        label-width="100px"
        class="settings-form"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="verification-code">
            <el-input v-model="emailForm.code" placeholder="请输入验证码">
              <template #prefix>
                <el-icon><Ticket /></el-icon>
              </template>
            </el-input>
            <el-button
              type="primary"
              :disabled="isCountingDown"
              @click="handleSendCode"
              :loading="sendingCode"
            >
              {{ countDownText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleChangeEmail"
            :loading="emailLoading"
          >
            <el-icon><Check /></el-icon> 绑定邮箱
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import {
  Lock,
  Key,
  EditPen,
  Check,
  Message,
  Ticket,
  RefreshRight,
} from "@element-plus/icons-vue";
import {
  type PasswordChangeForm,
  type EmailBindingForm,
  changePassword,
  changeEmail,
  sendVerificationCode,
} from "@/api/user";
import { useUserStore } from "@/store";

defineOptions({
  name: "AccountSettingView",
});

// 密码表单
const passwordFormRef = ref<FormInstance>();
const passwordForm = reactive<PasswordChangeForm>({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
const passwordLoading = ref(false);

// 邮箱表单
const emailFormRef = ref<FormInstance>();
const emailForm = reactive<EmailBindingForm>({
  email: "",
  code: "",
});
const emailLoading = ref(false);
const sendingCode = ref(false);
const countDown = ref(0);
const isCountingDown = ref(false);
const countDownText = ref("发送验证码");

// 密码校验规则
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { message: "密码长度不能小于8位", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, message: "密码长度不能小于8位", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "密码只能包含字母和数字",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: "blur" },
  ],
});

// 邮箱校验规则
const emailRules = reactive<FormRules>({
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 4, message: "验证码长度应为4位", trigger: "blur" },
  ],
});
const userStore = useUserStore();

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        passwordLoading.value = true;
        await changePassword(passwordForm);
        ElMessage.success("密码修改成功");
        userStore.userInfo = undefined;
        userStore.clearUserData();
        window.location.reload();
        window.location.href = "/login";
        // 重置表单
        passwordFormRef.value?.resetFields();
      } catch (error: any) {
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};

// 发送验证码
const handleSendCode = async () => {
  if (!emailFormRef.value) return;

  await emailFormRef.value.validateField("email", async (valid) => {
    if (valid) {
      try {
        sendingCode.value = true;
        await sendVerificationCode(emailForm.email!, "EMAIL");
        ElMessage.success("验证码发送成功");
        startCountDown();
      } catch (error: any) {
        ElMessage.error(error.message || "验证码发送失败");
      } finally {
        sendingCode.value = false;
      }
    }
  });
};

// 倒计时
const startCountDown = () => {
  countDown.value = 60;
  isCountingDown.value = true;
  const timer = setInterval(() => {
    countDown.value--;
    countDownText.value = `${countDown.value}秒后重新发送`;
    if (countDown.value <= 0) {
      clearInterval(timer);
      isCountingDown.value = false;
      countDownText.value = "发送验证码";
    }
  }, 1000);
};

// 绑定邮箱
const handleChangeEmail = async () => {
  if (!emailFormRef.value) return;

  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        emailLoading.value = true;
        await changeEmail(emailForm);
        ElMessage.success("邮箱绑定成功");
        // 重置表单
        emailFormRef.value?.resetFields();
      } catch (error: any) {
      } finally {
        emailLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.account-settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.settings-section {
  padding: 24px 0;
  position: relative;
}

.settings-section:not(:last-child) {
  border-bottom: 1px solid #eee;
}

.settings-section h3 {
  margin: 0 0 24px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.settings-section h3 .el-icon {
  color: #409eff;
  font-size: 20px;
}

.settings-form {
  max-width: 500px;
}

.verification-code {
  display: flex;
  gap: 12px;
}

.verification-code .el-input {
  flex: 1;
}

:deep(.el-input .el-input__prefix) {
  color: #909399;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: none;
  border: 1px solid #dcdfe6;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff;
}

@media (max-width: 768px) {
  .account-settings-container {
    padding: 16px;
  }

  .settings-section {
    padding: 20px 0;
  }

  .verification-code {
    gap: 8px;
  }
}
</style>
